package util.tree;


import java.util.LinkedList;

public class TreeUtil {
    public static TreeNode createTreeByLevel(Integer[] treeNodes) {
        int i = 1;
        TreeNode root = new TreeNode(treeNodes[0]);// 根节点
        TreeNode current = null;
        Integer value = 0;


        //层序创建二叉树
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (i < treeNodes.length) {
            current = queue.poll();//从链表中移除并获取第一个节点
            value = treeNodes[i++];
            if (value != null) {
                TreeNode left = new TreeNode(value);
                current.left = left;//创建当前节点的左孩子
                queue.offer(left); // 在链表尾部 左孩子入队
            }
            value = treeNodes[i++];
            if (value != null) {
                TreeNode right = new TreeNode(value);
                current.right = right;//创建当前节点的右孩子
                queue.offer(right);// 在链表尾部 右孩子入队
            }
        }
        return root;
    }
}
